package demo.java.lang.management.vo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang.StringUtils;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class JsonUtils implements Serializable{

	private static final long serialVersionUID = -4067763405310397425L;

    //导致fastjson反解析失败，需要删除的非法字符集
    private static final char[] illegalRemovedChars = {
            '\u001A'//play的播放数据显示的^Z导致泛解析失败，是个end-of-file字符
    };

	public static <T> String toJson(T o) {
		String s = "";
	    s = JSON.toJSONString(o, SerializerFeature.DisableCircularReferenceDetect);
		return s;
	}
	
	public static <T> List<T> fromJsonArray(String json, Class<T> clazz) {
		List<T> list = new ArrayList<T>();
		list = JSON.parseArray(json, clazz);
		return list;
	}

	public static <T>  T fromJson(String json, Class<T> clazz) {
        for (int i=0;i<illegalRemovedChars.length;i++){
            json = StringUtils.remove(json, illegalRemovedChars[i]);
        }
		return JSON.parseObject(json, clazz);
	}
	
	
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		XmlySpan span = new XmlySpan();
		span.setTraceId("22222");
		span.setSpanId("4444");
		span.getProps().put("User-Agent", "ting_4.1.7(anboAB001ÌQ,Android19)");
		span.getProps().put("started_at", "2015-08-11T09:39:40");
		String cityString  = new String("上海".getBytes(), "UTF-8");
		String cityString2  = new String(cityString.getBytes(), "UTF-8");
		span.getProps().put("x-city", cityString2);
		String string =  JsonUtils.toJson(span);
		System.out.println(string);
		XmlySpan span1 = JsonUtils.fromJson(string, XmlySpan.class);
		System.out.println(span1.getTraceId());
	}
}
